package com.justreading.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.justreading.order.constant.MessageConstant;
import com.justreading.order.entity.*;
import com.justreading.order.exception.SeatsNotEnoughException;
import com.justreading.order.service.*;
import com.justreading.order.vo.request.TravelOrderListRequest;
import com.justreading.order.vo.response.TravelOrderListResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.justreading.common.utils.PageUtils;
import com.justreading.common.utils.Query;

import com.justreading.order.dao.TravelOrderDao;
import org.springframework.transaction.annotation.Transactional;


@Service("travelOrderService")
public class TravelOrderServiceImpl extends ServiceImpl<TravelOrderDao, TravelOrderEntity> implements TravelOrderService {

    @Autowired
    private TravelListService travelListService;

    @Autowired
    private CarService carService;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    private static final String ORDER_MESSAGE_TAG_NAME = " 姓名: ";

    private static final String ORDER_MESSAGE_TAG_MOBILE = " 手机号码: ";

    private static final String ORDER_MESSAGE_TAG_OTHER = " 的用户: ";

    private static final Lock lock = new ReentrantLock();

    @Override
    public PageUtils queryPage(TravelOrderListRequest request) {
        String limit = request.getLimit();
        String currentPage = request.getPage();
        Long travelOrderUserId = request.getTravelOrderUserId();
        int page = Integer.parseInt(currentPage);
        if(page != 0){
            page = Integer.parseInt(limit) * page;
        }
        List<TravelOrderEntity> travelOrderEntities = this.baseMapper.pageList(page, Integer.parseInt(limit), travelOrderUserId);
        List<TravelOrderListResponse> responseList = travelOrderEntities.stream().map((entity) -> {
            TravelOrderListResponse travelOrderListResponse = new TravelOrderListResponse();
            BeanUtils.copyProperties(entity, travelOrderListResponse);
            TravelListEntity travelListEntity = travelListService.getById(entity.getTravelListId());
            travelOrderListResponse.setTravelPoint(travelListEntity.getTravelPoint());
            travelOrderListResponse.setBoardingPoint(travelListEntity.getBoardingPoint());
            travelOrderListResponse.setTravelTime(travelListEntity.getTravelTime());
            travelOrderListResponse.setCreateTime(entity.getCreateTime());
            travelOrderListResponse.setUpdateTime(entity.getUpdateTime());
            CarEntity carEntity = carService.getById(travelListEntity.getCarId());
            travelOrderListResponse.setLicensePlate(carEntity.getLicensePlate());
            return travelOrderListResponse;
        }).collect(Collectors.toList());
        IPage<TravelOrderListResponse> responseIPage = new Page<>(Long.parseLong(currentPage), Long.parseLong(limit));
        responseIPage.setRecords(responseList);
        return new PageUtils(responseIPage);
    }

    @Override
    public List<TravelOrderEntity> getTravelOrderByUserId(Long userId) {
        return this.list(new QueryWrapper<TravelOrderEntity>().eq("travel_order_user_id", userId));
    }

    /**
     * 预约出行
     * @param travelOrder
     */
    @Transactional
    @Override
    public void  saveOrderAndSendMessage(TravelOrderEntity travelOrder) {
        lock.lock();
        try{
            TravelListEntity travelListEntity = travelListService.getById(travelOrder.getTravelListId());
            if(travelListEntity.getSeats() <= 0){
                throw new SeatsNotEnoughException();
            }else{
                //1、增加预约
                this.save(travelOrder);

                //2、减少座位
                travelListEntity.setSeats(travelListEntity.getSeats() - 1);
                travelListService.updateById(travelListEntity);


                //3、发送车主消息
                MessageEntity travelListUserMessage = new MessageEntity();
                travelListUserMessage.setSendUserId(travelOrder.getTravelOrderUserId());
                travelListUserMessage.setReceiveUserId(travelOrder.getTravelListUserId());
                travelListUserMessage.setContent(ORDER_MESSAGE_TAG_NAME + travelOrder.getTravelOrderUserTrueName() + ORDER_MESSAGE_TAG_MOBILE + travelOrder.getTravelOrderUserMobile() +
                        ORDER_MESSAGE_TAG_OTHER + MessageConstant.ORDER_OWNER_SUCCESS);
                messageService.save(travelListUserMessage);

                //4、发送乘客消息
                MessageEntity travelOrderMessage = new MessageEntity();
                travelOrderMessage.setSendUserId(travelOrder.getTravelListUserId());
                travelOrderMessage.setReceiveUserId(travelOrder.getTravelOrderUserId());
                travelOrderMessage.setContent(MessageConstant.ORDER_USER_SUCCESS + "车主为:" + travelOrder.getTravelListUserTrueName() + "的 " + travelListEntity.getBoardingPoint() +"——>" + travelListEntity.getTravelPoint() + " 约单，请按时到达乘车地点");
                messageService.save(travelOrderMessage);
            }
        } catch (SeatsNotEnoughException e){
            throw e;
        }catch (Exception e){
            throw e;
        }finally{
           lock.unlock();
        }
    }

    /**
     * 更改约单状态
     */
    @Transactional
    @Override
    public void updateOrderAndSendMessage(TravelOrderEntity travelOrderEntity) {
        Integer orderStatus = travelOrderEntity.getOrderStatus();

        if(orderStatus.equals(4)){ //为4 直接删除

            this.removeById(travelOrderEntity.getId());


            //2、增加座位
            TravelListEntity travelListEntity = travelListService.getById(travelOrderEntity.getTravelListId());
            travelListEntity.setSeats(travelListEntity.getSeats() + 1);
            travelListService.updateById(travelListEntity);

            //3、发送车主消息
            MessageEntity travelListUserMessage = new MessageEntity();
            travelListUserMessage.setSendUserId(travelOrderEntity.getTravelOrderUserId());
            travelListUserMessage.setReceiveUserId(travelOrderEntity.getTravelListUserId());
            travelListUserMessage.setContent(ORDER_MESSAGE_TAG_NAME + travelOrderEntity.getTravelOrderUserTrueName() + ORDER_MESSAGE_TAG_MOBILE + travelOrderEntity.getTravelOrderUserMobile() +
                    ORDER_MESSAGE_TAG_OTHER + MessageConstant.ORDER_OWNER_CANCEL);
            messageService.save(travelListUserMessage);

            //4、发送乘客消息
            MessageEntity travelOrderMessage = new MessageEntity();
            travelOrderMessage.setSendUserId(travelOrderEntity.getTravelListUserId());
            travelOrderMessage.setReceiveUserId(travelOrderEntity.getTravelOrderUserId());
            travelOrderMessage.setContent(MessageConstant.ORDER_USER_CANCEL + " 车主为:" + travelOrderEntity.getTravelListUserTrueName() + "的 " + travelListEntity.getBoardingPoint() +"——>" + travelListEntity.getTravelPoint() + "的预约");
            messageService.save(travelOrderMessage);
        }else{
            this.updateById(travelOrderEntity);
        }
    }
}